<template>
  <van-row>
    <van-col offset="1" span="22">
      <van-form @submit="onSubmit">
        <van-field
          v-model="user.username"
          name="用户名"
          placeholder="请输入用户名"
          :rules="[
          { required: true, message: '请输入用户名' },
          { pattern, message: '请输入正确格式' }
          ]"
        />
        <van-field
          v-model="user.password"
          type="password"
          name="密码"
          placeholder="请输入密码"
          :rules="[
          { required: true, message: '请输入密码' },
          { validator, message: '请输入正确格式' }
          ]"
        />
        <div>
          <van-button round block type="info" native-type="submit">登录</van-button>

          <!-- 下面是摆设 -->
          <div class="regis">
            <router-link to="/my/MyTab/register">免费注册 &gt;</router-link>
            <router-link to>手机账号取回密码 &gt;</router-link>
          </div>
        </div>
        <div class="ord_login">
          <van-col>使用其他账号登录</van-col>
        </div>
      </van-form>
    </van-col>
  </van-row>
</template>

<script>
import {Toast} from "vant"
import login from "@/api/login";
export default {
  data() {
    return {
      user: {
        username: "",
        password: ""
      },
      pattern: /^[\da-zA-Z_]{6,18}$/
    };
  },
  methods: {
    onSubmit() {
      this.checkLogin();
    },
    validator(val) {
      return /^(?!\d+$)[\da-zA-Z]{6,18}$/.test(val);
    },
    async checkLogin() {
      try {
        let p = await this.$store.dispatch("Login", this.user);
        if (p.flag) {
          const toast = Toast.loading({
            duration: 0, // 持续展示 toast
            forbidClick: true,
            message: "登录中..."
          });

          let second = 2;
          const timer = setInterval(async () => {
            second--;
            if (second) {
              toast.message = `登录成功`;
            } else {
              clearInterval(timer);
              // 手动清除 Toast
              Toast.clear();
              this.$router.push("/my/MyCenter");
                let c = await this.$store.dispatch("getcart", this.user.username);
                if (!c.flag) {
                  this.$toast.fail("获取失败");
          }
            }
          }, 1000);
          
        } else {
          this.$message.error("用户名或密码错误");
        }
      } catch (err) {
        console.log(err);
        return false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
#login1 {
  width: 100%;
  height: 400px;
  background: darkcyan;
}
#username {
  width: 100%;
  height: 30px;
}
.van-button--info {
  background: rgb(184, 28, 34);
  border: none;
  border-radius: 2px;
  margin: 38px 0 10px 0;
}
.van-cell {
  margin: 20px 0;
  background: rgb(245, 245, 245);
}
.regis {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  margin-bottom: 23px;
  a {
    color: gray;
  }
}
.ord_login {
  font-size: 12px;
  color: gray;
}
</style>